import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [file, setFile] = useState(null);
  const [previewUrl, setPreviewUrl] = useState('');
  const [result, setResult] = useState('');

  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];
    if (selectedFile) {
      setFile(selectedFile);
      setPreviewUrl(URL.createObjectURL(selectedFile));
    }
  };

  const handleSubmit = async () => {
    if (!file) return;

    const formData = new FormData();
    formData.append('image', file);

    try {
      // 上传文件到服务器
      const uploadResponse = await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      // 调用 LLM 模型服务器接口
      const llmResponse = await axios.post('/api/recognize', {
        imageUrl: uploadResponse.data.imageUrl
      });

      setResult(llmResponse.data.result);
    } catch (error) {
      console.error('上传或识别失败:', error);
    }
  };

  return (
    <div className="App">
      <h1>图片识别应用</h1>
      <input type="file" accept="image/*" onChange={handleFileChange} />
      <button onClick={handleSubmit}>确定</button>
      {previewUrl && (
        <div>
          <h2>图片预览</h2>
          <img src={previewUrl} alt="预览" style={{ maxWidth: '100%' }} />
        </div>
      )}
      {result && (
        <div>
          <h2>识别结果</h2>
          <p>{result}</p>
        </div>
      )}
    </div>
  );
}

export default App;